<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars 
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY		= PRIMARY_KEY;
$PRIMARY_VALUE	= GetParam($PRIMARY_KEY,"");
$FileName				= "ais_transaction_dnbook.php";
$FileTemplate		= "ais_transaction_dnbook_form.html";
$SubHeaderTitle = "Transaction Account Receivable - Debit Note From Booking";
$TableName			= "ais_memorial";
$HTMLFormName		= "DNSummaryForm";
$MaxGrid				= "100";
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("memorial_id"=>"","uraian"=>"","uraian_a"=>"","noref"=>"0","noorder"=>"","urut"=>"","dk"=>"","skada"=>"","jumlah"=>"number","uraian_a"=>"","uraian_b"=>"","uraian_c"=>"","uraian_d"=>"");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
	if (GetParam("FormAction","")=="Save") {
		list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
		$tglbkt  = "$year-$month-$day";

		list($day,$month,$year) = explode("/",GetParam("arrdat",""));
		$arrdat  = "$year-$month-$day";

		list($day,$month,$year) = explode("/",GetParam("depdat",""));
		$depdat  = "$year-$month-$day";

		$rate    = StrToNumber (GetParam("rate",""));

		if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")	{
			$TransNo = SaveNumber("ND", GetParam("port",""), GetParam("tglbkt",""));
			FormSave("ais_memorial", "uraian", $FormFields, array("debtur"=>GetParam("debtur",""),"debnam"=>GetParam("debnam",""),"ledger"=>GetPeriod(GetParam("tglbkt","")),"curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"nobkt"=>$TransNo,"ktrasl"=>GetOfficeID(),"kdbank"=>GetParam("kdbank",""),"princ"=>GetParam("princ",""),"vessel"=>GetParam("vessel",""),"voyage"=>GetParam("voyage",""),"port"=>GetParam("port",""),"depdat"=>$depdat,"prtto"=>GetParam("prtto",""),"prtfrm"=>GetParam("prtfrm",""),"arrdat"=>$arrdat),"memorial_id");

			$DBConnection->add_data("ais_memorial","urut","999");
			$DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
			$DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
			$DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
			$DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
			$DBConnection->add_data("ais_memorial","kdact",GetParam("kdact",""));
			$DBConnection->add_data("ais_memorial","rate",$rate);
			$DBConnection->add_data("ais_memorial","nobkt",$TransNo);
			$DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
			$DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
			$DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
			$DBConnection->add_data("ais_memorial","debtur",GetParam("debtur",""));
			$DBConnection->add_data("ais_memorial","debnam",GetParam("debnam",""));
			$DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
			$DBConnection->add_data("ais_memorial","princ",GetParam("princ",""));
			$DBConnection->add_data("ais_memorial","vessel",GetParam("vessel",""));
			$DBConnection->add_data("ais_memorial","voyage",GetParam("voyage",""));
			$DBConnection->add_data("ais_memorial","port",GetParam("port",""));
                        
            $DBConnection->add_data("ais_memorial","depdat",$depdat);
            $DBConnection->add_data("ais_memorial","prtto",GetParam("prtto",""));
            $DBConnection->add_data("ais_memorial","prtfrm",GetParam("prtfrm",""));
            $DBConnection->add_data("ais_memorial","arrdat",$arrdat);
                        
			$DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
			$DBConnection->add_data("ais_memorial","jumlah",StrToNumber(GetParam("total_trans","")));
			$DBConnection->add_data("ais_memorial","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
			$DBConnection->add_data("ais_memorial","noref",StrToNumber(GetParam("noref1","")));
			$DBConnection->InsertGrid();
//			$DBConnection->dbc->debug();

			$DBConnection->add_data("ais_piutang","normut","999");
			$DBConnection->add_data("ais_piutang","ktrasl",GetOfficeID());
			$DBConnection->add_data("ais_piutang","ledger",GetPeriod(GetParam("tglbkt","")));
			$DBConnection->add_data("ais_piutang","curr",GetParam("curr",""));
			$DBConnection->add_data("ais_piutang","rate",$rate);
			$DBConnection->add_data("ais_piutang","nobkt",$TransNo);
			$DBConnection->add_data("ais_piutang","nobkta",$TransNo);
			$DBConnection->add_data("ais_piutang","tglbkt",$tglbkt);
			$DBConnection->add_data("ais_piutang","dk",GetParam("dk999",""));
			$DBConnection->add_data("ais_piutang","debtur",GetParam("debtur",""));
			$DBConnection->add_data("ais_piutang","debnam",GetParam("debnam",""));
			$DBConnection->add_data("ais_piutang","skada",GetParam("skada999",""));
			$DBConnection->add_data("ais_piutang","uraian",GetParam("uraian999",""));
			$DBConnection->add_data("ais_piutang","jumlah",StrToNumber(GetParam("total_trans","")));
			$DBConnection->add_data("ais_piutang","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
			$DBConnection->add_data("ais_piutang","noref",StrToNumber(GetParam("noref1","")));
			$DBConnection->InsertGrid();
//			$DBConnection->dbc->debug();
			SetLogActivity($TransNo,"Create","");

	    } else {
		    $TransNo = GetParam("nobkt","");		    
			$DBConnection->dbc->query("DELETE FROM ais_memorial WHERE ktrasl='".GetOfficeID()."' AND nobkt='".$TransNo."' ");
			$DBConnection->dbc->query("DELETE FROM ais_piutang WHERE ktrasl='".GetOfficeID()."' AND nobkt='".$TransNo."' ");

			FormSave("ais_memorial", "uraian", $FormFields, array("debtur"=>GetParam("debtur",""),"debnam"=>GetParam("debnam",""),"ledger"=>GetPeriod(GetParam("tglbkt","")),"curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"nobkt"=>$TransNo,"ktrasl"=>GetOfficeID(),"kdbank"=>GetParam("kdbank",""),"princ"=>GetParam("princ",""),"vessel"=>GetParam("vessel",""),"voyage"=>GetParam("voyage",""),"port"=>GetParam("port",""),"depdat"=>$depdat,"prtto"=>GetParam("prtto",""),"prtfrm"=>GetParam("prtfrm",""),"arrdat"=>$arrdat),"memorial_id");

			$DBConnection->add_data("ais_memorial","urut","999");
			$DBConnection->add_data("ais_memorial","ktrasl",GetOfficeID());
			$DBConnection->add_data("ais_memorial","kdbank",GetParam("kdbank",""));
			$DBConnection->add_data("ais_memorial","ledger",GetPeriod(GetParam("tglbkt","")));
			$DBConnection->add_data("ais_memorial","curr",GetParam("curr",""));
			$DBConnection->add_data("ais_memorial","kdact",GetParam("kdact",""));
			$DBConnection->add_data("ais_memorial","rate",$rate);
			$DBConnection->add_data("ais_memorial","nobkt",$TransNo);
			$DBConnection->add_data("ais_memorial","source","From BL");
			$DBConnection->add_data("ais_memorial","tglbkt",$tglbkt);
			$DBConnection->add_data("ais_memorial","dk",GetParam("dk999",""));
			$DBConnection->add_data("ais_memorial","noorder",GetParam("noorder999",""));
			$DBConnection->add_data("ais_memorial","debtur",GetParam("debtur",""));
			$DBConnection->add_data("ais_memorial","debnam",GetParam("debnam",""));
			$DBConnection->add_data("ais_memorial","skada",GetParam("skada999",""));
			$DBConnection->add_data("ais_memorial","princ",GetParam("princ",""));
			$DBConnection->add_data("ais_memorial","vessel",GetParam("vessel",""));
			$DBConnection->add_data("ais_memorial","voyage",GetParam("voyage",""));
			$DBConnection->add_data("ais_memorial","port",GetParam("port",""));

            $DBConnection->add_data("ais_memorial","depdat",$depdat);
            $DBConnection->add_data("ais_memorial","prtto",GetParam("prtto",""));
            $DBConnection->add_data("ais_memorial","prtfrm",GetParam("prtfrm",""));
            $DBConnection->add_data("ais_memorial","arrdat",$arrdat);

			$DBConnection->add_data("ais_memorial","uraian",GetParam("uraian999",""));
			$DBConnection->add_data("ais_memorial","jumlah",StrToNumber(GetParam("total_trans","")));
			$DBConnection->add_data("ais_memorial","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
			$DBConnection->add_data("ais_memorial","noref",StrToNumber(GetParam("noref1","")));
			$DBConnection->InsertGrid();
//			$DBConnection->dbc->debug();

			$DBConnection->add_data("ais_piutang","normut","999");
			$DBConnection->add_data("ais_piutang","ktrasl",GetOfficeID());
			$DBConnection->add_data("ais_piutang","ledger",GetPeriod(GetParam("tglbkt","")));
			$DBConnection->add_data("ais_piutang","curr",GetParam("curr",""));
			$DBConnection->add_data("ais_piutang","rate",$rate);
			$DBConnection->add_data("ais_piutang","nobkt",$TransNo);
			$DBConnection->add_data("ais_piutang","nobkta",$TransNo);
			$DBConnection->add_data("ais_piutang","tglbkt",$tglbkt);
			$DBConnection->add_data("ais_piutang","dk",GetParam("dk999",""));
			$DBConnection->add_data("ais_piutang","debtur",GetParam("debtur",""));
			$DBConnection->add_data("ais_piutang","debnam",GetParam("debnam",""));
			$DBConnection->add_data("ais_piutang","skada",GetParam("skada999",""));
			$DBConnection->add_data("ais_piutang","uraian",GetParam("uraian999",""));
			$DBConnection->add_data("ais_piutang","jumlah",StrToNumber(GetParam("total_trans","")));
			$DBConnection->add_data("ais_piutang","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
			$DBConnection->add_data("ais_piutang","noref",StrToNumber(GetParam("noref1","")));
			$DBConnection->InsertGrid();
//			$DBConnection->dbc->debug();
			SetLogActivity($TransNo,"Update","");
		}

                //register_shutdown_function ("GenerateCache");

		header("Location: $FileName?PageMode=Form");
		exit;

	}
	if (GetParam("FormAction","")=="Delete") {
//		print "Deleted"."<br>\n";
        $SQL = "DELETE FROM  ais_memorial WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_piutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        $SQL = "DELETE FROM  ais_hutang WHERE nobkt='".GetParam("nobkt","")."'";
        $DBConnection->dbc->query($SQL);
        SetLogActivity($TransNo,"Delete","");
		header("Location: $FileName?PageMode=Form");
		exit;
	}
}

//Field Verification 
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nobkt"=>"ID No.",
					  "tglbkt"=>"Transaction Date",
					  "port"=>"Port",
					  "curr"=>"Currency",
					  "kdact"=>"Activity Code",
					  "uraian999"=>"Uraian On Line 999","uraian1"=>"Uraian On Line 1",
                                          "skada999"=>"COA On Line 999");
					  
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,array("uraian_a1"=>"Remark On Line 1"));


if (GetParam(PRIMARY_KEY,"")) {
	$SQLCount     = "SELECT count(*) FROM `$TableName`";
	$SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."' "."AND ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut<>999";;
	$Count        = $DBConnection->dbc->get_var($SQLCount);	
} else $Count=0;

$NewDataStart = $Count + 1;
$InitFunction = "Masking();Masking2();";

$VerifyGrids = array("uraian"=>"0","jumlah"=>"number","skada"=>"","dk"=>"");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("rate"=>"number","tglbkt"=>"date","arrdat"=>"date","depdat"=>"date"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) $FormMode = "Edit";
else $FormMode = "Add";

//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY ".PRIMARY_KEY;
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Bank:
$SQLBank = "SELECT * FROM tblbank ORDER BY banknam";
//Select Kantor
$SQLKtr  = "SELECT * FROM tblkantor ORDER BY ktrasl";
//Select Account Actvty
$SQLAct  = "SELECT * FROM tblactivity ORDER BY actname ";

//$HeaderFields = array("nokwit"=>"0","tglkwit"=>"date","curr"=>"","rate"=>"number","kdbank"=>"0");
$HeaderFields = array("nobkt"=>"","tglbkt"=>"date","curr"=>"","kdact"=>"","rate"=>"number","debtur"=>"","debnam"=>"","voyage"=>"","vessel"=>"","princ"=>"","port"=>"","depdat"=>"date","prtto"=>"","prtfrm"=>"","arrdat"=>"date");
//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= " WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);

$SQL999 = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$SQL999 = $SQL999." AND urut = 999";

$TBS->MergeBlock("dept999blk",$DBMysql,$SQLDept);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("blg9",$DBMysql,$SQL999);}
else $TBS->MergeBlock("blg9",$FormCValue);

// HTML Value
$TBS->MergeBlock("headbln",$FormHName);
$TBS->MergeBlock("princblk",GetArrayPrincipal());
$TBS->MergeBlock("portblk",GetArrayPort());
$TBS->MergeBlock("fromportblk",GetArrayPort());
$TBS->MergeBlock("toportblk",GetArrayPort());
$TBS->MergeBlock("vesselblk",GetArrayVessel());
$TBS->MergeBlock("voyageblk",GetArrayVoyage());
$TBS->MergeBlock("dayblk",GetArrayDay());
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);


if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormHValue);


//********************************* HTML GRID *********************************************
//HTML Grid
$SQLGrid = "SELECT * FROM ais_memorial "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut<>999";
//print $SQLGrid;
$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************

function FormInsert() {
	global $DBConnection,$FileName;
	$DBConnection->Insert();
	header("Location: $FileName?PageMode=Form");
	exit;
}

function FormUpdate() {
	global $DBConnection;
	$DBConnection->Update();
}

function FormDelete() {
	global $DBConnection,$FileName,$TableName;
	$DBConnection->deleteGrid("$TableName","nobkt");
	header("Location: $FileName");
	exit;	
}

function FormSearch () {

}

function FormCancel () {
	global $FileName;
	header("Location: ".$FileName."?PageMode=List");
	exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
	global $FileName, $MaxGrid, $DBConnection;
	$TotalData = $MaxGrid * 2;	
	$NewDataStart = GetParam("NewData","0");
	$NewDataStart = 1;

	for ($a=1;$a<=$TotalData;$a++) {
		foreach ($FormFields as $key=>$formatting) {
			if (!GetParam($keyField.$a,"")) {
				print GetParam($keyField.$a,"");
				$EndOfData = 1;
				break;
			}
			$value = GetParam($key.$a,"");
			if ($formatting=="number") $value = str_replace(",","",$value);
			if ($formatting=="date") {
				list($day,$month,$year) = explode("/",$value);
				$value = "$year-$month-$day";
		    }
			$DBConnection->add_data($table,$key,$value);
		}
		$rate = StrToNumber(GetParam("rate",""));
		$jmh  = StrToNumber(GetParam("jumlah".$a,""));
		$rupiah = $rate * $jmh;
		$DBConnection->add_data($table,"rupiah",$rupiah);
		if ($EndOfData) {
			break;
	    }
		if (strlen($SpecialCase)) {
			foreach ($SpecialCase as $key => $value) {
			//	print "add_data($table,$key,$value);<br>";
				$DBConnection->add_data($table,$key,$value);
			}
		}
//		print "$a < $NewDataStart<br>";
		if ($a < $NewDataStart) {
			 if (strlen($PrimaryKey)) {
			    $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
		 	 } else {
			    $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
		     }
		} else {
			$DBConnection->InsertGrid();
	    }
	}
	$DBConnection->ClearData();
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
		global $DBConnection;
		for ($x=0;$x<count($arrayfield);$x++) {
			$DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
		}
}

function DeleteRecord ($sequence_name,$PageSize) {
	global $DBConnection,$FileName,$TableName;	
	for ($x=1;$x<=$PageSize;$x++) {				
		if (GetParam($sequence_name.$x,""))	{
			$DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
	    }
	}
}

function BuildFields ($FormFields) {
		global $DBConnection;
		$str = "";
		foreach ($FormFields as $key=>$formatting) {
			if (strlen($str)) $str .= ",$key";
			else $str = "$key";
		}
		return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
		global $DBConnection;
		$array_fields = array();
		for ($x=0;$x<$MaxGrid;$x++) {
			foreach ($FormFields as $key=>$formatting){
				$a=$x+1;
				$array_fields[$key.$a] = "$formatting";
			}			
		}
		return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
	global $DBConnection;

	if ($tmp) $TEMPORARY = "TEMPORARY";
	$DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

	$SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
	if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
	$MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
	if (!$MyResult) return false;
 	$session_file = substr(md5(time()), 0, 8);
   	$session_file = "/tmp/".$session_file.".tmp";
	BufferToFile ($MyResult,$session_file);

	$DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);   	
	$SQL = "DROP TABLE IF EXISTS `$TableName`;";
	$DBConnection->dbc->query($SQL);

	$SQL= "CREATE $TEMPORARY TABLE `$TableName` (
			  `kodecustomer` varchar(20) NOT NULL default '',
			  `nama` varchar(50) default NULL,
			  `cr_term` int(4) default NULL,
			  `kdtype` varchar(20) default NULL
			  )";
	$DBConnection->dbc->query($SQL);

   	$SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
	$DBConnection->dbc->query($SQL);
	unlink($session_file);
	return true;
}

function GetLastDateReport() {
	global $DBConnection;
	list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
	$current_date = "$year-$month-$day";

        $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
	if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";                
        $DBConnection->dbc->query($SQL);
        //$DBConnection->dbc->debug();

	$SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
	if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";        
        
	return $DBConnection->dbc->get_var($SQL);
}


function GenerateCache() {
		 	global $DBConnection;
			//$TEMP = "TEMPORARY";

		 	if (!FlushCustomer ("ais_customer", 1)) return false;
			//$current_date = date("Y-m-d",mktime (0,0,0,GetParam("m",""),1,GetParam("y","")));

			list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
			$current_date = "$year-$month-$day";
			$LastDate  = GetLastDateReport();

			$SQL = "DROP TABLE IF EXISTS `ais_piutang_terhutang`";
			$DBConnection->dbc->query($SQL);

			$SQL = "
					CREATE $TEMP TABLE `ais_piutang_terhutang` (
					  `ktrasl` varchar(5) default NULL,
					  `tglbkt` date,
					  `nobkt` varchar(16) default NULL,	
                                          `nobkta` varchar(16) default NULL,
					  `debtur` varchar(16) default NULL,
					  `debnam` varchar(32) default NULL,
					  `uraian` text default NULL,
					  `curr` varchar(4) default NULL,
					  `jumlah` varchar(32) default NULL,
					  `cr_term` tinyint(4)default NULL,
                                          `top_curr` date,
                                          `top_30` date,
                                          `top_60` date,
                                          `aging` varchar(16)
					);
				   ";
			$DBConnection->dbc->query($SQL);

			$SQL = "
					INSERT INTO ais_piutang_terhutang
					SELECT KTRASL, TGLBKT, NOBKT,NOBKTA, ais_customer.kodecustomer, ais_customer.nama, URAIAN, CURR, JUMLAH, IFNULL(CR_TERM,0) AS TOP, 

					ADDDATE( tglbkt,INTERVAL ais_customer.cr_term DAY ) as top_curr,
					ADDDATE( tglbkt,INTERVAL 30+ais_customer.cr_term DAY ) as top_30,
					ADDDATE( tglbkt,INTERVAL 60+ais_customer.cr_term DAY ) as top_60,

                                        IF('$current_date'<=ADDDATE( tglbkt,INTERVAL ais_customer.cr_term DAY ),'0',
                                        IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 30+ais_customer.cr_term DAY ),'30',
                                        IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 60+ais_customer.cr_term DAY ),'60','60g')))

					FROM ais_piutang
					LEFT JOIN ais_customer ON ais_piutang.DEBTUR=ais_customer.kodecustomer
					WHERE srt='1' AND ais_piutang.tglbkt<='$current_date'
				   ";

			if (strlen($LastDate))
			$SQL .= "AND ais_piutang.tglbkt>'$LastDate' ";
			
			if (GetParam("skada999","")) 
			$SQL .= "AND ais_piutang.skada >= '".GetParam("skada999","")."' ";

			if (GetParam("curr","")) 
			$SQL .= "AND ais_piutang.curr = '".GetParam("curr","")."' ";

			if (GetParam("skada999",""))
			$SQL .= "AND ais_piutang.skada <= '".GetParam("skada999","")."' ";

                        //print $SQL;die();
			if (GetOfficeID())  $SQL .= "AND ais_piutang.ktrasl = '".GetOfficeID()."' ";

			$SQL .= "order by nobkt ";
			$DBConnection->dbc->query($SQL);

			$SQL = "DROP TABLE IF EXISTS `ais_piutang_terbayar`";
			$DBConnection->dbc->query($SQL);

			$SQL = "
					CREATE $TEMP TABLE `ais_piutang_terbayar` (
					  `nobkt` varchar(16) default NULL,					  
					  `nobkta` varchar(16) default NULL,
                      `bayar` decimal(15,3) default NULL,
					  `debtur` varchar(64) default NULL,					  
					  `debnam` varchar(128) default NULL                                          
					) ;
				   ";
			$DBConnection->dbc->query($SQL);

			$SQL = "
					INSERT INTO ais_piutang_terbayar
					SELECT NOBKT, NOBKTA, SUM(JUMLAH),debtur,debnam
					FROM ais_piutang
                                        LEFT JOIN ais_customer ON ais_piutang.DEBTUR=ais_customer.kodecustomer
					WHERE srt='2' AND ais_piutang.tglbkt<='$current_date' ";

			if (strlen($LastDate))
			$SQL .= "AND ais_piutang.tglbkt>'$LastDate' ";

                        //print $SQL;die();
			if (GetOfficeID())  
                        $SQL .= "AND ais_piutang.ktrasl = '".GetOfficeID()."' ";

			if (GetParam("curr","")) 
			$SQL .= "AND ais_piutang.curr = '".GetParam("curr","")."' ";

            $SQL .= "group by nobkta order by nobkta";
                        //print $SQL;die();
			$DBConnection->dbc->query($SQL);
			//$DBConnection->dbc->debug();

//Auto Update Using Cache Begin Here
			 if (strlen($LastDate)) {

				$SQL = "DROP TABLE IF EXISTS `ais_piutang_sisa_period`";
				$DBConnection->dbc->query($SQL);

				$SQL = "
						CREATE $TEMP TABLE `ais_piutang_sisa_period` (
						  `ktrasl` varchar(5) default NULL,
						  `tglbkt` date,
						  `aging_date` date,					  
						  `nobkt` varchar(16) default NULL,
						  `debtur` varchar(16) default NULL,
						  `debnam` varchar(32) default NULL,
						  `uraian` text default NULL,
                                                  `cr_term` tinyint(4)default NULL,
						  `jumlah` decimal(15,2) default NULL,
                                                  `aging` varchar(16),
                                                  `fromskada` varchar(16),
                                                  `toskada` varchar(16),
                                                  `curr`varchar(5)
						)
					   ";
				$DBConnection->dbc->query($SQL);
	             $SQL = "
	                      INSERT INTO ais_piutang_sisa_period
	                      SELECT *
	                      FROM ais_piutang_sisa
	                      WHERE aging_date='$LastDate' AND fromskada='".GetParam("skada999","")."' AND toskada='".GetParam("skada999","")."'
						";
                              if (GetParam("curr",""))  $SQL .= " AND curr='".GetParam("curr","")."' ";
                              
				 $DBConnection->dbc->query($SQL);

                       $SQL = " 
	             		  INSERT INTO ais_piutang_sisa_period
	                      SELECT ktrasl,tglbkt,'$current_date',nobkt,debtur,debnam,uraian,cr_term,jumlah,aging,'".GetParam("skada999","")."','".GetParam("skada999","")."','".GetParam("curr","")."'
	                      FROM ais_piutang_terhutang
	                    ";
				 $DBConnection->dbc->query($SQL);


		             $SQL = "
		                      INSERT INTO ais_piutang_sisa
		                      SELECT 
		                      ais_piutang_sisa_period.ktrasl,
		                      ais_piutang_sisa_period.tglbkt,
		                      '$current_date',
		                      ais_piutang_sisa_period.nobkt,
		                      ais_piutang_sisa_period.debtur,
		                      ais_piutang_sisa_period.debnam,
		                      ais_piutang_sisa_period.uraian,
		                      ifnull(ais_piutang_sisa_period.cr_term, 0) AS top,
		                      ifnull(ais_piutang_sisa_period.jumlah,0)-ifnull(ais_piutang_terbayar.bayar,0),

			                  IF('$current_date'<=ADDDATE( tglbkt,INTERVAL ais_piutang_sisa_period.cr_term DAY ),'0',
			                  IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 30+ais_piutang_sisa_period.cr_term DAY ),'30',
			                  IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 60+ais_piutang_sisa_period.cr_term DAY ),'60','60g'))),
                                          '".GetParam("skada999","")."','".GetParam("skada999","")."','".GetParam("curr","")."'

		                      FROM
		                      ais_piutang_sisa_period
		                      LEFT JOIN ais_piutang_terbayar ON (ais_piutang_sisa_period.nobkt = ais_piutang_terbayar.nobkta)
		                      WHERE (ifnull(ais_piutang_terbayar.nobkt, '') = '') OR ifnull(ais_piutang_sisa_period.jumlah-ais_piutang_terbayar.bayar,0) <> 0
		                      ORDER BY debtur,nobkt
		                    ";
					 $DBConnection->dbc->query($SQL);

			 } else {
		             $SQL = "
		                      INSERT INTO ais_piutang_sisa
		                      SELECT 
		                      ais_piutang_terhutang.ktrasl,
		                      ais_piutang_terhutang.tglbkt,
		                      '$current_date',
		                      ais_piutang_terhutang.nobkt,
		                      ais_piutang_terhutang.debtur,
		                      ais_piutang_terhutang.debnam,
		                      ais_piutang_terhutang.uraian,
		                      ifnull(ais_piutang_terhutang.cr_term, 0) AS top,
		                      ifnull(ais_piutang_terhutang.jumlah,0)-ifnull(ais_piutang_terbayar.bayar,0),
		                      
		                    IF('$current_date'<=ADDDATE( tglbkt,INTERVAL ais_piutang_terhutang.cr_term DAY ),'0',
		                    IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 30+ais_piutang_terhutang.cr_term DAY ),'30',
		                    IF('$current_date'<=ADDDATE( tglbkt,INTERVAL 60+ais_piutang_terhutang.cr_term DAY ),'60','60g'))),
                                          '".GetParam("skada999","")."','".GetParam("skada999","")."','".GetParam("curr","")."'
                                          
		                      FROM
		                      ais_piutang_terhutang
		                      LEFT JOIN ais_piutang_terbayar ON (ais_piutang_terhutang.nobkt = ais_piutang_terbayar.nobkta)
		                      WHERE (ifnull(ais_piutang_terbayar.nobkt, '') = '') OR ifnull(ais_piutang_terhutang.jumlah-ais_piutang_terbayar.bayar,0) <> 0
		                      ORDER BY debtur,nobkt
		                    ";
					$DBConnection->dbc->query($SQL);

			}
//Auto Update Using Cache End Here

//			$SQL = "SELECT * FROM ais_aging WHERE aging_date='$current_date'";

}
?>